const XLSX = require("xlsx");
const pdf = require("pdf-parse");
const fs = require("fs");
const path = require("path");

// const resultPath = path.resolve(__dirname, "统计结果");

const xlsRead = (xlsPath) => {
  // 读取Excel词库
  const workbook = XLSX.readFile(xlsPath);
  const worksheet = workbook.Sheets[workbook.SheetNames[0]];

  const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

  let result = [];

  data.forEach((row, rowIndex) => {
    if (rowIndex > 0) {
      let obj = {
        序号: 0,
        教材: row[0],
        课本: row[1],
        单元: row[2],
        频次: 0,
        英文: row[3],
        中文: row[4],
        音标: row[5],
      };

      result.push(obj);
    }
  });

  return result;
};

const pdfRead = (result, pdfPath, resultFileName) => {
  let dataBuffer = fs.readFileSync(pdfPath);

  pdf(dataBuffer).then(function (data) {
    const pdfText = data.text;

    result.forEach((item) => {
      const regex = new RegExp(item["英文"], "gi");
      const matches = pdfText.match(regex);
      item["频次"] = matches ? matches.length : 0;
    });

    result = result.filter((i) => i["频次"] > 0);

    result.forEach((i, index) => {
      i["序号"] = index + 1;
    });

    // 导出统计结果到Excel
    const resultWorkbook = XLSX.utils.book_new();
    const resultWorksheet = XLSX.utils.json_to_sheet(result);

    XLSX.utils.book_append_sheet(resultWorkbook, resultWorksheet, "统计结果");

    XLSX.writeFile(resultWorkbook, `result/${resultFileName}.xlsx`);
  });
};

// 清空文件夹
const resetFileDir = (resourcePath) => {
  // 文件夹存在清空内容，如果不存在则创建
  if (!fs.existsSync(resourcePath)) {
    fs.mkdirSync(resourcePath);
  } else {
    if (fs.existsSync(resourcePath)) {
      fs.readdirSync(resourcePath).forEach((file) => {
        const filePath = path.join(resourcePath, file);
        if (fs.lstatSync(filePath).isDirectory()) {
          fs.rmdirSync(filePath, { recursive: true });
        } else {
          fs.unlinkSync(filePath);
        }
      });
    }
  }
};

module.exports = { pdfRead, xlsRead, resetFileDir };
